package com.yupi.project.service.impl;

import com.yupi.project.common.ErrorCode;
import com.yupi.project.exception.BusinessException;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


@Service
public class RedissonManager {

    @Resource
    RedissonClient redissonClient;
    public void tryAcquire(String key) {
        //创建限流器
        RRateLimiter rateLimiter = redissonClient.getRateLimiter(key);
        //设置限流器的参数
        rateLimiter.trySetRate(RateType.OVERALL,2,1,RateIntervalUnit.SECONDS);
        //每一次请求获取1个令牌
        if (!rateLimiter.tryAcquire(1)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求过多");
        }
    }
}
